import { generateRandomId } from '@/lib/utils';
import { OperationMessage, useMessageStore } from '@/store/message';

export function useMessage() {
  const dispatch = useMessageStore((state) => state.dispatch);

  function resetMessage() {
    dispatch({
      type: 'update',
      update(draftState) {
        draftState.operationMessages = [];
      },
    });
  }

  function addMessage(message: Omit<OperationMessage, 'id'>) {
    dispatch({
      type: 'update',
      update(draftState) {
        draftState.operationMessages.push({
          ...message,
          id: generateRandomId(),
        });
      },
    });
  }

  function resetAndAddMessage(message: Omit<OperationMessage, 'id'>) {
    dispatch({
      type: 'update',
      update(draftState) {
        // 移除所有相关类型的信息
        const catetory = message.category;
        const firstMessageIndex = draftState.operationMessages.findIndex(
          (item) => item.category === catetory,
        );
        if (firstMessageIndex > -1) {
          // 执行替换操作
          draftState.operationMessages = draftState.operationMessages.filter(
            (item) => item.category !== catetory,
          );
          // 在对应的位置中插入,可以保证顺序不乱
          draftState.operationMessages.splice(firstMessageIndex, 0, {
            ...message,
            id: generateRandomId(),
          });
        } else {
          draftState.operationMessages.push({
            ...message,
            id: generateRandomId(),
          });
        }
      },
    });
  }

  return {
    resetMessage: useCallback(resetMessage, []),
    addMessage: useCallback(addMessage, []),
    resetAndAddMessage: useCallback(resetAndAddMessage, []),
  };
}
